package com.example.loginProject.interceptor;

import com.example.loginProject.exception.ServiceException;
import com.example.loginProject.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * token拦截器
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String method = request.getMethod();
        if (method.equals("OPTIONS")){
            //不拦取
            return true;
        }
        String token = request.getHeader("Authorization");
        if(token == null){
            throw new ServiceException("用户未登录");
        }
        try{
            String userId = TokenUtil.getUserId(token);
            String to = (String)redisTemplate.opsForValue().get(userId);
            TokenUtil.checkSign(to);

        }catch (Exception e){
            e.printStackTrace();
            // extendmapper.updateloginoutstatus(JwtUtil.getUserId(token));
            throw new ServiceException("token无效，请重新登入");
        }
        return true;
    }
}